package com.seemygo.shop.cloud.web.controller;

import com.seemygo.shop.cloud.domain.User;
import com.seemygo.shop.cloud.exception.BusinessException;
import com.seemygo.shop.cloud.redis.key.SeckillRedisKey;
import com.seemygo.shop.cloud.util.CookieUtil;
import com.seemygo.shop.cloud.util.VerifyCodeImgUtil;
import com.seemygo.shop.cloud.web.SeckillCodeMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
@RequestMapping("/api/verify/code")
public class VerifyCodeController extends BaseController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping
    public void generate(Long seckillId, String userToken, HttpServletResponse response) throws IOException {
        User user = getCurrentUser(userToken);
        if (user == null || seckillId == null) {
            throw new BusinessException(SeckillCodeMsg.OP_ERROR);
        }

        // 1. 生成验证码
        String exp = VerifyCodeImgUtil.generateVerifyCode();
        Integer ret = VerifyCodeImgUtil.calc(exp);
        // 2. 将验证码的结果保存到redis
        redisTemplate.opsForValue().set(
                SeckillRedisKey.SECKILL_VERIFY_CODE.join(seckillId+"", user.getId()+""),
                ret + "",
                SeckillRedisKey.SECKILL_VERIFY_CODE.getExpireTime(),
                SeckillRedisKey.SECKILL_VERIFY_CODE.getUnit());

        // 3. 将生成的验证码图片响应回前端
        BufferedImage verifyCodeImg = VerifyCodeImgUtil.createVerifyCodeImg(exp);
        response.setContentType("image/jpg");
        // 将生成的图片的输入流，按照指定格式，输出到http响应对象的输出流中，最终响应到浏览器
        ImageIO.write(verifyCodeImg, "JPEG", response.getOutputStream());
    }
}
